<template>
  <h1>用户登录</h1>
  <form @submit.prevent="submitToLogin">
    <div>账号：<input v-model="user.username" type="text" /></div>
    <div>密码：<input v-model="user.password" type="password" /></div>
    <button type="submit">登录/注册</button>
  </form>
</template>

<script>
import { defineComponent, reactive } from "vue";
import axios from "axios";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

export default defineComponent({
  setup() {
    const user = reactive({
      username: "",
      password: "",
    });
    const router = useRouter();
    const store = useStore();

    const submitToLogin = async () => {
      try {
        const { data } = await axios.post(
          "http://localhost:3000/api/login",
          user
        );
        store.commit("setUser", data.user);
        router.push("/");
      } catch (error) {
        const { error: message } = error.response.data;
        alert(message);
      }
    };

    return {
      user,
      submitToLogin,
    };
  },
});
</script>

<style></style>
